from fastapi import APIRouter, Depends, HTTPException
from typing import List, Optional
from pydantic import BaseModel, ValidationError
from datetime import datetime
from sqlalchemy.orm import Session
from ..database import get_db
from ..models.shop import Product, Shop, Category, CategoryResponse, BaseConfiguration
from .auth import get_current_active_user

router = APIRouter()

class ProductBase(BaseModel):
    item_name: str
    item_brand: Optional[str] = None
    item_specs: Optional[str] = None
    item_price: float
    item_classification: Optional[str] = None
    base_price: Optional[float] = None
    base_unit: Optional[str] = None
    shop_id: int
    shop_name: str
    sku_id: str
    item_img: str
    run_id: str
    created_at: Optional[datetime] = None


class ProductCreate(ProductBase):
    pass

class ProductResponse(ProductBase):
    id: int
    created_at: datetime

    class Config:
        from_attributes = True

class ShopBase(BaseModel):
    shop_name: Optional[str] = None
    shipping_address: Optional[str] = None
    logo_img: Optional[str] = None
    shop_address: Optional[str] = None
    longitude: Optional[str] = None
    latitude: Optional[str] = None
    provincia_level_name: Optional[str] = None
    municipa_level_name: Optional[str] = None
    district_level_name: Optional[str] = None
    region_name: Optional[str] = None
    enabled: Optional[str] = None
    final_exec_timestamp: Optional[datetime] = None
    item_count: Optional[int] = None
    present_state: Optional[str] = None
    store_id: Optional[int] = None

class ShopCreate(ShopBase):
    pass

class ShopResponse(ShopBase):
    id: int
    created_at: Optional[datetime] = None

    class Config:
        from_attributes = True

class CategoryCreate(BaseModel):
    category_id: str
    category_name: str
    first_category_id: Optional[str] = None
    first_category_name: Optional[str] = None
    category_type: Optional[str] = None

class BaseConfigurationBase(BaseModel):
    login_id: str
    device_id: str
    v: str
    app_version: str
    request_version: str
    free_version: str

class BaseConfigurationCreate(BaseConfigurationBase):
    pass

class BaseConfigurationResponse(BaseConfigurationBase):
    id: int
    created_at: Optional[datetime] = None

    class Config:
        from_attributes = True

"""
创建新商品
---
参数:
- product: 商品创建模型，包含名称、描述、价格、分类ID、库存和店铺ID
- db: 数据库会话
- current_user: 当前登录用户

返回:
- 201: 创建成功，返回商品详情
- 400: 创建失败，输入数据有误
"""
@router.post("/products/", response_model=ProductResponse, status_code=201)
async def create_product(
    product: ProductCreate,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_active_user)
):
    db_product = Product(**product.dict())
    db.add(db_product)
    try:
        db.commit()
        db.refresh(db_product)
        return db_product
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail="商品创建失败，请检查输入数据")
    
"""
批量新增商品
---
参数:
- products: 商品创建模型列表
- db: 数据库会话
- current_user: 当前登录用户

"""
@router.post("/products/batch", response_model=List[ProductResponse], status_code=201)
async def create_products(
    products: List[ProductCreate],
    db: Session = Depends(get_db),
    current_user = Depends(get_current_active_user)
):
    db_products = [Product(**product.dict()) for product in products]
    db.add_all(db_products)
    try:
        db.commit()
        # 刷新每个对象
        for product in db_products:
            db.refresh(product)
        return db_products
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail="商品创建失败，请检查输入数据")
    
"""
获取所有商品列表
---
参数:
- skip: 跳过的记录数（分页用）
- limit: 返回的最大记录数（分页用）
- db: 数据库会话

返回:
- 200: 返回商品列表和总数
"""
@router.get("/products/")
async def get_products(
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db)
):
    # 获取总数
    total = db.query(Product).count()
    # 获取分页数据
    products = db.query(Product).offset(skip).limit(limit).all()
    return {
        "items": products,
        "total": total
    }

"""
获取商品详情
---
参数:
- product_id: 商品ID
- db: 数据库会话

返回:
- 200: 返回商品详细信息
- 404: 商品不存在
"""
@router.get("/products/{product_id}", response_model=ProductResponse)
async def get_product(
    product_id: int,
    db: Session = Depends(get_db)
):
    product = db.query(Product).filter(Product.id == product_id).first()
    if not product:
        raise HTTPException(status_code=404, detail="商品不存在")
    return product

"""
更新商品信息
---
参数:
- product_id: 商品ID
- product: 更新的商品信息
- db: 数据库会话
- current_user: 当前登录用户

返回:
- 200: 更新成功，返回更新后的商品信息
- 404: 商品不存在
- 400: 更新失败，输入数据有误
"""
@router.put("/products/{product_id}", response_model=ProductResponse)
async def update_product(
    product_id: int,
    product: ProductCreate,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_active_user)
):
    db_product = db.query(Product).filter(Product.id == product_id).first()
    if not db_product:
        raise HTTPException(status_code=404, detail="商品不存在")
    
    for key, value in product.dict().items():
        setattr(db_product, key, value)
    
    try:
        db.commit()
        db.refresh(db_product)
        return db_product
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail="商品更新失败，请检查输入数据")

"""
删除商品
---
参数:
- product_id: 商品ID
- db: 数据库会话
- current_user: 当前登录用户

返回:
- 200: 删除成功
- 404: 商品不存在
"""
@router.delete("/products/{product_id}")
async def delete_product(
    product_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_active_user)
):
    product = db.query(Product).filter(Product.id == product_id).first()
    if not product:
        raise HTTPException(status_code=404, detail="商品不存在")
    
    db.delete(product)
    db.commit()
    return {"message": "商品删除成功"}

"""
创建新店铺
---
参数:
- shop: 店铺创建模型，包含名称、描述、地址和联系方式
- db: 数据库会话
- current_user: 当前登录用户

返回:
- 201: 创建成功，返回店铺详情
- 400: 创建失败，输入数据有误
"""
@router.post("/shops/", response_model=ShopResponse, status_code=201)
async def create_shop(
    shop: ShopCreate,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_active_user)
):
    
    # 通过store_id和shop_address查询数据库，判断当前数据是否存在
    existing_shop = db.query(Shop).filter(Shop.shop_name == shop.shop_name, Shop.store_id == shop.store_id, Shop.shop_address == shop.shop_address).first()
    if existing_shop:
        raise HTTPException(status_code=400, detail="店铺已存在")

    db_shop = Shop(**shop.dict())
    db.add(db_shop)
    try:
        db.commit()
        db.refresh(db_shop)
        return db_shop
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail="店铺创建失败，请检查输入数据")

"""
获取店铺详情
---
参数:
- id: 店铺ID
- db: 数据库会话

返回:
- 200: 返回店铺详细信息
- 404: 店铺不存在
"""
@router.get("/shops/{id}", response_model=ShopResponse)
async def get_shop(
    id: int,
    db: Session = Depends(get_db)
):
    shop = db.query(Shop).filter(Shop.id == id).first()
    if not shop:
        raise HTTPException(status_code=404, detail="店铺不存在")
    return shop

"""
更新店铺信息
---
参数:
- id: 店铺ID
- shop: 更新的店铺信息
- db: 数据库会话
- current_user: 当前登录用户

返回:
- 200: 更新成功，返回更新后的店铺信息
- 404: 店铺不存在
- 400: 更新失败，输入数据有误
"""
@router.put("/shops/{id}", response_model=ShopResponse)
async def update_shop(
    id: int,
    shop: ShopBase,  # 改用 ShopBase 而不是 ShopCreate，因为更新时字段是可选的
    db: Session = Depends(get_db),
    current_user = Depends(get_current_active_user)
):
    try:
        db_shop = db.query(Shop).filter(Shop.id == id).first()
        if not db_shop:
            raise HTTPException(status_code=404, detail="店铺不存在")
        
        # 只更新提供的字段
        update_data = shop.dict(exclude_unset=True)
        for key, value in update_data.items():
            setattr(db_shop, key, value)
        
        try:
            db.commit()
            db.refresh(db_shop)
            return db_shop
        except Exception as e:
            db.rollback()
            raise HTTPException(status_code=400, detail=f"店铺更新失败: {str(e)}")
    except ValidationError as e:
        raise HTTPException(status_code=422, detail=str(e.errors()))
    

"""
获取店铺的所有商品
---
参数:
- id: 店铺ID
- db: 数据库会话

返回:
- 200: 返回该店铺的所有商品列表
"""
@router.get("/shops/{id}/products", response_model=List[ProductResponse])
async def get_shop_products(
    id: int,
    db: Session = Depends(get_db)
):
    products = db.query(Product).filter(Product.shop_id == id).all()
    return products

"""
获取所有商品分类
---
参数:
- db: 数据库会话

返回:
- 200: 返回所有商品分类列表
"""
@router.get("/categories/", response_model=List[CategoryResponse])
async def get_categories(
    db: Session = Depends(get_db)
):
    categories = db.query(Category).all()
    return [category.to_response() for category in categories]

"""
创建新的商品分类
---
参数:
- category: 分类创建模型，包含名称和描述
- db: 数据库会话
- current_user: 当前登录用户

返回:
- 201: 创建成功，返回分类详情
- 400: 创建失败，输入数据有误
"""
@router.post("/categories/", response_model=CategoryResponse, status_code=201)
async def create_category(
    category: CategoryCreate,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_active_user)
):
    try:
        db_category = Category(
            category_id=category.category_id,
            category_name=category.category_name,
            first_category_id=category.first_category_id,
            first_category_name=category.first_category_name,
            category_type=category.category_type
        )
        db.add(db_category)
        db.commit()
        db.refresh(db_category)
        return db_category.to_response()
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=f"分类创建失败：{str(e)}")

"""
根据id获取配置信息
---
参数:
- id: 配置信息ID
- db: 数据库会话

返回:
- 200: 配置信息
- 404: 配置信息不存在
"""
@router.get("/base_configuration/{id}", response_model=BaseConfigurationResponse)
async def get_base_configuration(
    id: int,
    db: Session = Depends(get_db)
):
    try:
        # 根据id查询配置信息
        base_configuration = db.query(BaseConfiguration).filter(BaseConfiguration.id == id).first()
        if not base_configuration:
            raise HTTPException(status_code=404, detail="配置信息不存在")
        return base_configuration
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取配置信息失败: {str(e)}")
